# -*- coding: utf-8 -*-
# @Time    :2022/1/17 20:16
# @AUTHOR  :MORAN
# @Email   :moran@maqu.com
# @File    :verifyUtil.py
# @Software:PyCharm
import os
import random
import string

from PIL import Image, ImageFont, ImageDraw, ImageFilter


class ImageVerify:
    """
    图像验证码
    """

    def __init__(self, length=4, width=140, height=40, size=28):
        """
        初始化图片的信息
        :param length: 4
        :param width: 140
        :param height: 40
        :param size: 28
        """
        self.length = length
        self.width = width
        self.height = height
        self.size = size

    def random_str(self):
        """
        随机生成字符串
        26个大小写字母和10个数字
        :return: 验证码字符串
        """
        # string.ascii_letters + ''.join([str(i) for i in range(0, 10)])
        source = string.ascii_letters + string.digits
        return ''.join(random.sample(source, self.length))

    def random_color(self, start=0, end=255):
        """
        随机RGB颜色
        :param start: 初始值
        :param end: 结束值
        :return: tuple(r,g,b)
        """
        res = (random.randint(start, end) for i in range(3))
        return tuple(res)

    def random_lines(self, draw):
        """
        绘制干扰线
        :param draw: draw对象
        :return:
        """
        for i in range(self.length):
            lines = [(random.randint(0, self.width), random.randint(0, self.height)) for i in range(2)]
            draw.line(list(lines), fill=self.random_color(40, 240), width=2)

    def random_points(self, draw, rate):
        """
        绘制干扰点
        :param draw: 画
        :param rate: 频率
        :return:
        """
        for x in range(self.width):
            for y in range(self.height):
                if random.randint(0, 100) <= rate:
                    draw.point((x, y), fill=self.random_color(40, 240))

    def verify_code(self):
        """
        生成验证码
        :return: tuple(图片，验证码)
        """
        # 创建画布，创建image对象 底图
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))  # 白色背景图

        # 创建字体(font)对象
        file = os.path.dirname(os.path.abspath(__file__))
        font = ImageFont.truetype(f'{file}/simplifiedFont.ttf', self.size)

        # 创建画笔(draw)对象
        draw = ImageDraw.Draw(image)

        # 绘制干扰
        self.random_lines(draw)
        self.random_points(draw, 15)

        # 验证码
        code = self.random_str()

        # 将随机颜色的验证码写到图片上
        for i in range(self.length):
            draw.text((30*i, 3), code[i], font=font, fill=self.random_color(60, 200))

        # 模糊化
        image = image.filter(ImageFilter.BLUR)
        return image, code


if __name__ == '__main__':
    imageverify = ImageVerify()
    image, code = imageverify.verify_code()
    with open('test.png', 'wb') as fb:
        image.save(fb)
    print(code)

